package com.example.demo.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.custom.AjaxResult;
import com.example.demo.custom.BaseController;
import com.example.demo.entity.XiMei;
import com.example.demo.entity.XiMei2;
import com.example.demo.form.XiMeiForm;
import com.example.demo.service.XiMei2Service;
import com.example.demo.service.XiMeiService;

@RestController
@RequestMapping(value = "/ximei2")
public class XiMei2Controller {
	@Autowired
	private XiMei2Service service2;
	@Autowired
	private XiMeiService service1;
	
	private DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");

	
	@RequestMapping(value = "/save")
	public Object save(XiMeiForm form) throws ParseException {
		Integer id = form.getId();
		Date d=new Date();
		Date d1=dateFormat1.parse("1999-01-01");
		XiMei ximei=new XiMei();
		XiMei xiMei3 =new XiMei();
		XiMei2 ximei2=new XiMei2();
		XiMei2 ximei22=new XiMei2();
		if(id==null) {
			ximei.setName(form.getName());
			xiMei3= service1.save(ximei);
		}else {
			xiMei3 = service1.findById(id);
			xiMei3.setName(form.getName());
			service1.save(xiMei3);
			List<XiMei2> list=service2.findByXiMeiId(xiMei3.getId());
			for(XiMei2 xi2 : list) {
				if(d1.compareTo(xi2.getBeginDate())==-1) {
					d1=xi2.getBeginDate();
					ximei22=xi2;
				}
			}
			ximei22.setEndDate(d);
			service2.save(ximei22);
		}
		BeanUtils.copyProperties(form, ximei2,"id","name");
		ximei2.setXiMei(xiMei3);
		ximei2.setBeginDate(d);
		service2.save(ximei2);
		return new AjaxResult("保存成功!");
	}
	
	@RequestMapping(value = "/list")
	public Object list() {
		return new AjaxResult(service1.findAll());
	}
	
	@RequestMapping(value = "/findbyId")
	public Object findbyId(Integer id) throws ParseException {
		List<XiMei2> list=service2.findByXiMeiId(id);
		DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");

		Date d = dateFormat1.parse("1999-01-01");
		XiMei2 yan=new XiMei2();
		for(XiMei2 y :list) {
			if(d.compareTo(y.getBeginDate())==-1) {
				d=y.getBeginDate();
				yan=y;
			}
		}
		return new AjaxResult(yan);
	}
	
	
}
